<!--
 * @Author: yaojian66 1327629137@qq.com
 * @Date: 2022-07-05 16:18:55
 * @LastEditors: yaojian66 1327629137@qq.com
 * @LastEditTime: 2022-07-05 16:19:12
 * @FilePath: \geyao\第一百一十三题 虚拟dom.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>虚拟dom</title>
</head>

<body>
  <!-- 
    析构对象参数中的tag、props、children、text值
    当tag的数据类型为”string“时，通过tag标签创建新节点并且挂载在vnode对象参数的el属性上
    再通过setAttribute函数给vnode.el节点设置属性
    然后通过appendChild、createTextNode将当前节点对象的text内容插入vnode.el节点上
    最后通过createElm函数递归children数组重复以上过程
    当tag的数据类型不为string时，直接通过createTextNode创建文本节点
 -->
  <script>
    var vnode = {
      tag: 'ul',
      props: {
        class: 'list'
      },
      text: '',
      children: [{
          tag: "li",
          props: {
            class: "item"
          },
          text: '',
          children: [{
            tag: undefined,
            props: {},
            text: '牛客网',
            children: []
          }]
        },
        {
          tag: "li",
          props: {},
          text: '',
          children: [{
            tag: undefined,
            props: {},
            text: 'nowcoder',
            children: []
          }]
        }
      ]
    }
    const _createElm = vnode => {
      let {
        tag,
        props,
        children,
        text
      } = vnode
      if (typeof tag == "string") {
        vnode.el = document.createElement(tag)
        _setAttr(vnode.el, props)
        vnode.el.appendChild(document.createTextNode(text))
        children.forEach(child => {
          vnode.el.appendChild(_createElm(child))
        })
      } else {
        vnode.el = document.createTextNode(text)
      }
      return vnode.el
    }
    const _setAttr = (elem, attrs) => {
      for (key in attrs) {
        elem.setAttribute(key, attrs[key])
      }
    }
  </script>
</body>

</html>